/**
 * JAVACC DEMO 1.0
 * @copy right iussoft company All rights reserved.
 * @Package com.iussoft.portal.thread
 */
package com.apache.portal.thread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * description:  线程调度类
 * @author Hou Dayu 创建时间：2016-12-29
 */
public class ThreadScheduler {

	private ScheduledExecutorService scheduExec;
	private static ThreadScheduler instance;
	private Map<String, JobConfig> threadMap = new HashMap<String, JobConfig>();

	private ThreadScheduler() {
		scheduExec = Executors.newScheduledThreadPool(2);
	}

	public static ThreadScheduler newInstance() {
		if (null == instance) {
			instance = new ThreadScheduler();
		}
		return instance;
	}

	/**
	 * description:  按KEY开启线程
	 * @param key   
	 */
	public void startBykey(String key) {
		JobConfig job = threadMap.get(key);
		if (null != job || !job.isOpen()) {
			startTask(job);
			threadMap.put(key, job);
		}
	}
	
	public boolean checkJob(String key){
		JobConfig job = threadMap.get(key);
		if(null != job){
			return false;
		}
		return true;
	}

	private void startTask(JobConfig job) {
		ScheduledFuture sf = scheduExec.scheduleAtFixedRate(job.getJob(), 0, job.getSleepInterval(),
				TimeUnit.MILLISECONDS);//.SECONDS);
		job.setOpen(true);
	}

	/**
	 * description:  插入线程对象
	 */
	public void setThreadMap(String key, JobConfig value) {
		this.threadMap.put(key, value);
	}
}
